import {CellStatus} from "../../utils/enum";
import {SkuCode} from "./sku-code";
import {SkuPending} from "./sku-pending";
import {Joiner} from "../../utils/joiner";

class Judger {
  fenceGroup
  pathDict = []
  skuPending

  constructor(fenceGroup) {
    this.fenceGroup = fenceGroup
    // 这个要先调用
    this._initPathDict()
    // 这个要后调用
    this._initSkuPending()
  }

  _initSkuPending(){
    this.skuPending = new SkuPending()
    const defaultSku = this.fenceGroup.getDefaultSku()
    if(!defaultSku){
      return
    }
    this.skuPending.init(defaultSku)
    this._initSelectedCell()
    this.judge(null, null, null, true)
  }
  _initSelectedCell(){
    this.skuPending.pending.forEach(cell=>{
      this.fenceGroup.setCellStatusById(cell.id, CellStatus.SELECTED)
    })
  }

  _initPathDict() {
    this.fenceGroup.spu.sku_list.forEach(s => {
      const skuCode = new SkuCode(s.code)
      this.pathDict = this.pathDict.concat(skuCode.totalSegments)
    })
  }

  judge(cell, x, y, isInit=false) {
    if(!isInit){
      this._changeCurrentCellStatus(cell, x, y)
    }
    //apply this指向问题
    //或者使用箭头函数解决this的指向问题
    this.fenceGroup.eachCell((cell, x, y)=>{
      const path = this._findPotentialPath(cell, x, y)
      // console.log(path)
      if(!path){
        return
      }
      const isIn = this._isInPathDict(path)
      if(isIn){
        this.fenceGroup.setCellStatusByXY(x, y, CellStatus.WAITING)
      }else{
        this.fenceGroup.setCellStatusByXY(x, y, CellStatus.FORBIDDEN)
      }
    })
  }

  _isInPathDict(path){
    return this.pathDict.includes(path)
  }

  _findPotentialPath(cell, x, y){
    const joiner = new Joiner('#')
    for(let i=0;i<this.fenceGroup.fences.length;i++){
        const selected = this.skuPending.findSelectedCellByX(i)
        if( x === i){
          //当前cell所在的行
          if(this.skuPending.isSelected(cell, x)){
            return
          }
          const cellCode = this._getCellCode(cell.spec)
          joiner.join(cellCode)
        }else{
          if(selected){
            const selectedCellCode = this._getCellCode(selected.spec)
            joiner.join(selectedCellCode)
          }
        }
    }
    return joiner.getStr()
  }

  _getCellCode(spec){
     return spec.spec_key_id + '-' + spec.spec_value_id
  }

  _changeCurrentCellStatus(cell, x, y) {
    if (cell.status === CellStatus.WAITING) {
      this.fenceGroup.setCellStatusByXY(x, y, CellStatus.SELECTED)
      // this.fenceGroup.fences[x].cells[y].status = CellStatus.SELECTED
      this.skuPending.insertCell(cell, x)
    }
    if (cell.status === CellStatus.SELECTED) {
      this.fenceGroup.setCellStatusByXY(x, y, CellStatus.WAITING)
      // this.fenceGroup.fences[x].cells[y].status = CellStatus.WAITING
      // console.log(this.fenceGroup.fences[x].cells[y].status)
      this.skuPending.removeCell(x)
    }
  }
}

export {
  Judger
}